package com.gzz.controller;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gzz.common.R;
import com.gzz.pojo.BaseInfo;
import com.gzz.pojo.Cart;
import com.gzz.pojo.GoodsInfo;
import com.gzz.pojo.SystemMessage;
import com.gzz.service.BaseInfoService;
import com.gzz.service.BasePositionService;
import com.gzz.service.GoodsInfoService;
import com.gzz.service.SystemMessageService;
import com.gzz.utils.JWTUtils;
import com.gzz.utils.RabbitMqUtils;
import com.gzz.vo.CartInfo;
import com.gzz.vo.SenceryDetailVo;
import com.gzz.vo.goodsOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static jdk.nashorn.internal.objects.NativeMath.round;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 */
@RestController
@Slf4j
@RequestMapping("/api/base-info")
public class    BaseInfoController {
    @Autowired
    BasePositionService basePositionService;
    @Autowired
    BaseInfoService baseInfoService;
    @Autowired
    GoodsInfoService goodsInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    SystemMessageService systemMessageService;
    @GetMapping("/pay")
    public R<String> pay(Long orderId){
        LambdaUpdateWrapper<BaseInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(BaseInfo::getOrderId,orderId).set(BaseInfo::getTab,2);
        baseInfoService.update(lambdaUpdateWrapper);
        return R.success("支付成功");
    }

     @PostMapping("/add")
    public R<List<String>> orderAdd(HttpServletRequest request, @RequestBody List<CartInfo> cartList)
     {
         log.info("进行中");
         String token = request.getHeader("token");

         Long id = JWTUtils.parseToken(token);

          List<BaseInfo> baseInfoList = new ArrayList<>();

          List<String> orderIdList = new ArrayList<>();

         System.out.println(cartList.get(0).getCartId()+"我的谓词");

          for(CartInfo cart : cartList)
          {

              Long orderId = (long)Math.abs(UUID.randomUUID().hashCode());

              BaseInfo baseInfo = new BaseInfo();

              baseInfo.setUserId(id);

              GoodsInfo goodsInfo = goodsInfoService.getById(cart.getGoodsId());

              double price = round(goodsInfo.getGoodsPrice().doubleValue()*cart.getGoodsNum(),2);

              baseInfo.setGoodsNum((long)cart.getGoodsNum());

              baseInfo.setOrderTime(DateTime.now());

              baseInfo.setOrderId(orderId.toString());

              baseInfo.setSumPrice(price);

              baseInfo.setTab(1);

              // 向rabbitmq发送订单创建的消息，实现超时订单自动取消
              rabbitTemplate.convertAndSend(RabbitMqUtils.order_exchange,RabbitMqUtils.order_routing_key,orderId,(message) -> {
                  //设置有效时间，如果消息不被消费，进入死信队列
                  message.getMessageProperties().setExpiration(RabbitMqUtils.order_expire);
                  return message;
              });


              baseInfo.setGoodsName(goodsInfo.getGoodsName());

              baseInfoList.add(baseInfo);

              orderIdList.add(orderId.toString());
          }
          baseInfoService.saveBatch(baseInfoList);

         log.info("内容为:"+cartList.get(0).toString());
              return R.success(orderIdList);
     }
     
     @PutMapping("/change")
    public R changeState(@RequestBody List<String> stringList)
     {
         UpdateWrapper<BaseInfo> baseInfoUpdateWrapper = new UpdateWrapper<>();

         baseInfoUpdateWrapper.in("order_Id",stringList);

         baseInfoUpdateWrapper.set("tab",2);

         baseInfoService.update(baseInfoUpdateWrapper);

         return R.success(true);
     }


     @GetMapping("/list")
    public R<List<goodsOrderVo>> getBaseInfoList(HttpServletRequest request)
     {
         String token = request.getHeader("token");

         Long id = JWTUtils.parseToken(token);

         QueryWrapper<BaseInfo> baseInfoQueryWrapper = new QueryWrapper<>();

         baseInfoQueryWrapper.eq("user_Id",id);
         baseInfoQueryWrapper.orderByDesc("order_Time");
         List<BaseInfo> baseInfoList = baseInfoService.list(baseInfoQueryWrapper);


         List<goodsOrderVo> res = new ArrayList<>();

         baseInfoList.forEach(item->{
             goodsOrderVo  OrderVo = new goodsOrderVo();
             BeanUtils.copyProperties(item,OrderVo);
             String name = item.getGoodsName();
             LambdaQueryWrapper<GoodsInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();

             lambdaQueryWrapper.eq(GoodsInfo::getGoodsName,name);
             GoodsInfo one = goodsInfoService.getOne(lambdaQueryWrapper);

             OrderVo.setGoodsPic(one.getGoodsPic());

             res.add(OrderVo);
         });
         return R.success(res);


     }

     @GetMapping("/adminlist")
    public R<PageInfo<BaseInfo>> getBaseInfoListbyAdmin(int pageNum,int pageSize, String search,Long userId,Integer status){
         PageHelper.startPage(pageNum,pageSize);
         R<List<BaseInfo>> r = baseInfoService.getBaseInfoListbyAdmin(search,userId,status);
         List<BaseInfo> list = r.getData();
         PageInfo<BaseInfo> pageInfo = new PageInfo<>(list);

         return R.success(pageInfo);
     }

     @GetMapping("/updateTab")
    public R<String> updateTab(String orderId,Integer tab){
         LambdaUpdateWrapper<BaseInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
         lambdaUpdateWrapper.eq(BaseInfo::getOrderId,orderId).set(tab!=null,BaseInfo::getTab,tab);
         boolean f = baseInfoService.update(lambdaUpdateWrapper);
         if(f){
             return R.success("修改成功");
         }else{
             return R.error("修改失败");
         }

     }
     @GetMapping("/adminUpdateTab")
     public R<String> adminupdateTab(String orderId,Integer tab){
         LambdaUpdateWrapper<BaseInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
         lambdaUpdateWrapper.eq(BaseInfo::getOrderId,orderId).set(tab!=null,BaseInfo::getTab,tab);
         boolean f = baseInfoService.update(lambdaUpdateWrapper);
         BaseInfo baseInfo = baseInfoService.getById(orderId);
         Long userId = baseInfo.getUserId();
         if(f){
             if(tab==3){
                 SystemMessage systemMessage = new SystemMessage();
                 Long id = (long)Math.abs(UUID.randomUUID().hashCode());
                 systemMessage.setId(id);
                 systemMessage.setTitle("商品信息");
                 systemMessage.setContext("你的商品发货啦！");
                 systemMessage.setUserId(userId);
                 systemMessage.setCreateTime(new Date());
                 systemMessageService.save(systemMessage);
             }
             return R.success("修改成功");
         }else{
             return R.error("修改失败");
         }

     }
}

